import {
  ArgumentsHost,
  BadRequestException,
  Catch,
  ExceptionFilter,
  Inject,
  RequestTimeoutException,
} from "@nestjs/common";
import { Response, Request } from "express";
/**
 *
 * 过滤器处理类型为HttpException的异常 及其子类的异常
 * 当异常未识别(既不是HttpException 也不是继承自HttpException的类),
 * 内置的异常过滤器会生成以下默认的JSON相应
 *  {"statusCode":500,"message":"Internal Server Error"}
 */
//只捕获特定类型的异常
@Catch(BadRequestException, RequestTimeoutException)
export class CustomExceptionFilter implements ExceptionFilter {
  constructor(@Inject("PREFIX") private readonly prefix) {}
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    response.status(status).json({
      statusCode: status,
      message: exception.getResponse()?.message
        ? exception.getResponse()?.message
        : exception.getResponse(),
      timestamp: new Date().toLocaleDateString(),
      path: request.originalUrl,
      method: request.method,
    });
  }
}
